#!/bin/sh

TEST_DIR=''

cleanup() {
  case "${TEST_DIR}" in
    /*) rm -rf "${TEST_DIR}" ;;
  esac
  unset -f nvm_test_tool 2>/dev/null
  alias nvm_test_tool='nvm_test_tool'
  unalias nvm_test_tool
}
die () { echo "$@" ; cleanup ; exit 1; }

: nvm.sh
\. ../../../nvm.sh

TEST_DIR="$(mktemp -d)" || die 'could not make a temp dir'
PATH="${TEST_DIR}:${PATH}"

OUTPUT="$(nvm_has_executable nvm_test_tool 2>&1)" && die 'with no nvm_test_tool, expected failure'
[ -z "${OUTPUT}" ] || die "with no nvm_test_tool, expected no output, got >${OUTPUT}<"

# defined before the alias, so zsh does not expand the alias in the definition
nvm_test_tool() { echo function; }
alias nvm_test_tool='echo alias'
OUTPUT="$(nvm_has_executable nvm_test_tool 2>&1)" && die 'with only a function and an alias, expected failure'
[ -z "${OUTPUT}" ] || die "with only a function and an alias, expected no output, got >${OUTPUT}<"
# called directly, not in a command substitution, so that a change to the caller would persist
nvm_has_executable nvm_test_tool && die 'with only a function and an alias, expected failure'
# the backslash skips the alias, but not the function
[ "_$(\nvm_test_tool)" = '_function' ] || die 'the caller lost its nvm_test_tool function'
alias nvm_test_tool >/dev/null 2>&1 || die 'the caller lost its nvm_test_tool alias'
unalias nvm_test_tool
unset -f nvm_test_tool

printf '#!/bin/sh\necho tool\n' > "${TEST_DIR}/nvm_test_tool"
chmod a+x "${TEST_DIR}/nvm_test_tool"

OUTPUT="$(nvm_has_executable nvm_test_tool 2>&1)" || die "expected success, got >${OUTPUT}<"
[ -z "${OUTPUT}" ] || die "expected no output, got >${OUTPUT}<"

# a removed file is gone, even while the shell still has its path hashed
OUTPUT="$(hash nvm_test_tool; command rm "${TEST_DIR}/nvm_test_tool"; nvm_has_executable nvm_test_tool 2>&1)" && die 'with nvm_test_tool removed but hashed, expected failure'
[ -z "${OUTPUT}" ] || die "with nvm_test_tool removed but hashed, expected no output, got >${OUTPUT}<"

cleanup
